import requests

# response = requests.get("http://www.baidu.com")
# print(response.text)

# response = requests.post('http://httpbin.org/post', data={'key': 'value'})
# print(response.text)

'''
import requests

url = "https://api.example.com/data"
headers = {"Authorization": "Bearer YOUR_TOKEN"}
params = {"page": 1, "limit": 10}

try:
    response = requests.get(url, headers=headers, params=params, timeout=10)
    response.raise_for_status()
    data = response.json()
    print(data)
except requests.exceptions.RequestException as e:
    print("请求失败:", e)
'''

'''
收获：将实际参数提取出来，存为变量，使其更灵活
'''

# 目标URL
url = "https://httpbin.org/post"

# 要发送的数据，可以是表单数据或JSON数据
# 这里以表单数据为例
data = {
    'username': 'testuser',
    'password': '12345'
}

# 设置自定义请求头
headers = {
    'User-Agent': 'my-app/0.0.1',
    'Content-Type': 'application/x-www-form-urlencoded'  # 如果发送的是表单数据
    # 'Content-Type': 'application/json'  # 如果发送的是JSON数据，请取消注释并删除上面一行
}

# 使用Session对象保持状态（如果需要）
session = requests.Session()

try:
    # 发送POST请求
    response = session.post(url, data=data, headers=headers)

    # 检查请求是否成功
    if response.status_code == 200:
        print("请求成功！")
        # 打印返回的数据
        print(response.json())
    else:
        print(f"请求失败，状态码：{response.status_code}")
        print(response.text)
except requests.exceptions.RequestException as e:
    # 处理可能发生的异常，如网络错误
    print(f"发生异常：{e}")